<?php
declare (strict_types=1);

namespace app\admin\validate\auth;

use app\admin\model\auth\SystemMenu;
use app\common\validate\BaseValidate;


class MenuValidate extends BaseValidate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'menu_id' => 'require|number',
        'title' => 'require|max:32',
        'path' => 'require',
        'component' => 'require',
        'hidden' => 'require|number|in:0,1',
    ];


    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'title.require' => '标题为必填项',
        'title.max' => '名称最多不能超过32个字符',
    ];

    protected $scene = [
        'create' => [
            'title',
            'path',
            'component',
            'hidden'
        ],

        'update' => [
            'menu_id',
            'title',
            'path',
            'component',
            'hidden'
        ],
    ];

    public function sceneDelete()
    {
        return $this->only(['menu_id'])
            ->append('menu_id', 'hasNotChildren');
    }

    protected function hasNotChildren($value)
    {
        /** @var SystemMenu $menu */
        $menu = SystemMenu::with('children')
            ->where('menu_id', '=', $value)
            ->find();
        if (empty($menu)) {
            return '未找到对应菜单';
        }
        if (count($menu->children) > 0) {
            return '请先移除子菜单' . count($menu->children);
        }
        return true;
    }

}
